package com.wbs.lease.common.utils;

import com.wbs.lease.common.exception.LeaseException;
import com.wbs.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @author 韦帮愫
 * @version 1.0
 */
@Component
public class JwtUtil {

    //过期时间
    private static long tokenExpiration = 60 * 60 * 1000L;
    //生成密钥
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    //创建token
    public static String createToken(Long userId, String username) {
        String token = Jwts.builder().
                setSubject("USER_INFO").
                setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                claim("userId", userId).
                claim("username", username).
                signWith(tokenSignKey).
                compact();
        return token;
    }

    //解析token
    public static Claims parseJWT(String token) {

        //校验token是否为空
        if (token == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        try {
            JwtParser jwtParser = Jwts.parserBuilder()
                    .setSigningKey(tokenSignKey)
                    .build();
            return  jwtParser.parseClaimsJwt(token).getBody();
        }catch (ExpiredJwtException e){//token过期
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){//token非法
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }

    }

}